<?php

namespace Fluency\Routing;

use Fluency\Dispatcher;
use Fluency\Request;

/**
 * @package Fluency\Routing
 * @author  Ignas Rudaitis
 * @version 2.0.0
 */
class RouterChain implements Router
{
    private $dispatcher;
    private $routers;

    public function __construct(Dispatcher $dispatcher, array $routers)
    {
        $this->dispatcher = $dispatcher;
        $this->routers = $routers;
    }

    public function createRequest($url)
    {
        foreach ($this->routers as $router) {
            if ($router instanceof Request) {
                return $router;
            }
            $result = $router->createRequest($url);
            if ($result !== null && $this->dispatcher->canDispatch($result)) {
                return $result;
            }
        }
    }

    public function createUrl($action, array $params = array())
    {
        foreach ($this->routers as $router) {
            if ($router instanceof Router) {
                $result = $router->createUrl($action, $params);
                if ($result !== null) {
                    return $result;
                }
            }
        }
    }
}